package com.fastjars.business.shiro.filter;

import com.fastjars.business.shiro.TokenHolder;
import com.fastjars.business.shiro.model.UserModel;
import com.fastjars.business.spring.http.Resp;
import org.apache.commons.util.RequestUtils;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Deque;
import java.util.LinkedList;

/**
 * SessionKickOutFilter
 * 多用户登录管理
 * @author Brant Liu <br>
 * 邮箱：lbf1988@qq.com <br>
 * 日期：2018/5/9
 * @version 1.0.0
 */
public class SessionKickOutFilter extends AccessControlFilter {
    private static final Logger LOGGER = LoggerFactory.getLogger(SessionKickOutFilter.class);
    public static final  String SHIRO_SESSION_KICK_OUT_CACHE_NAME = "shiro-kickout-session";
    public static final  String SHIRO_SESSION_KICK_OUT_ATTRIBUTE_NAME = "kickout";
    public static final  String SHIRO_SESSION_KICK_OUT_URL = "/kickout";

    private SessionManager sessionManager;

    private String cacheName = SHIRO_SESSION_KICK_OUT_CACHE_NAME;

    private Cache<String,Deque<Serializable>> cache;
    /**
     * 踢出之前登录的/之后登录的用户 默认踢出之前登录的用户
     */
    private boolean kickOutAfter = false;

    /**
     * 踢出用户跳转URL
     */
    private String redirectUrl = SHIRO_SESSION_KICK_OUT_URL;

    /**
     * 同一个帐号最大会话数 默认1
     */
    private int maxSession = 1;

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        Subject subject = getSubject(request, response);
        Session session = subject.getSession();
        UserModel userModel = TokenHolder.getToken();
        Serializable sessionId = session.getId();
        //TODO 同步控制
        Deque<Serializable> deque = cache.get(userModel.getMobile());
        if(deque == null) {
            deque = new LinkedList<Serializable>();
            cache.put(userModel.getMobile(), deque);
        }
        //如果队列里没有此sessionId，且用户没有被踢出；放入队列
        if(!deque.contains(sessionId) && session.getAttribute(SHIRO_SESSION_KICK_OUT_ATTRIBUTE_NAME) == null) {
            deque.push(sessionId);
        }
        //如果队列里的sessionId数超出最大会话数，开始踢人
        while(deque.size() > maxSession) {
            Serializable kickoutSessionId = null;
            if(kickOutAfter) { //如果踢出后者
                kickoutSessionId = deque.removeFirst();
            } else { //否则踢出前者
                kickoutSessionId = deque.removeLast();
            }
            try {
                Session kickOutSession = sessionManager.getSession(new DefaultSessionKey(kickoutSessionId));
                if(kickOutSession != null) {
                    //设置会话的kickout属性表示踢出了
                    kickOutSession.setAttribute(SHIRO_SESSION_KICK_OUT_ATTRIBUTE_NAME, true);
                }
            } catch (Exception e) {//ignore exception
                deque.remove(kickoutSessionId);
                cache.put(userModel.getMobile(), deque);
                LOGGER.debug("用户已经退出，删除");
            }
        }
        if (session.getAttribute(SHIRO_SESSION_KICK_OUT_ATTRIBUTE_NAME) != null) {
            return false;
        }
        return true;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        Subject subject = getSubject(request, response);
        try {
            subject.logout();
        }catch (SessionException ex){
        }
        super.saveRequest(request);
        if (RequestUtils.isAjaxRequest((HttpServletRequest) request)) {
            WriterUtils.write(response, Resp.otherLogin().build().toJsonString());
            return false;
        }
        WebUtils.issueRedirect(request, response, this.getRedirectUrl());
        return false;
    }

    public void setCacheManager(CacheManager cacheManager) {
        this.cache = cacheManager.getCache(getCacheName());
    }

    public SessionManager getSessionManager() {
        return sessionManager;
    }

    public void setSessionManager(SessionManager sessionManager) {
        this.sessionManager = sessionManager;
    }

    public String getCacheName() {
        return cacheName;
    }

    public void setCacheName(String cacheName) {
        this.cacheName = cacheName;
    }

    public boolean isKickOutAfter() {
        return kickOutAfter;
    }

    public void setKickOutAfter(boolean kickOutAfter) {
        this.kickOutAfter = kickOutAfter;
    }

    public String getRedirectUrl() {
        return redirectUrl;
    }

    public void setRedirectUrl(String redirectUrl) {
        this.redirectUrl = redirectUrl;
    }

    public int getMaxSession() {
        return maxSession;
    }

    public void setMaxSession(int maxSession) {
        this.maxSession = maxSession;
    }
}
